package net.maku.generator.utils;

import net.maku.generator.entity.GenTemplateTreeEntity;

import java.io.*;
import java.util.Date;

public class EntityCommUtils {

    public static void preprecessEntity(GenTemplateTreeEntity entity){
        Date current_time = new Date();
        entity.setCreateTime(current_time);
        entity.setReadmeFile(genreteMdFileName());
    }

    public static String moveFile(String basePath, String sourceFilePath, String sourcePath, String targetPath) {
        String targetFilePath = sourceFilePath.replaceAll(sourcePath, targetPath);
        File sourceFile =  new File(basePath + sourceFilePath);
        File targetFile =  new File(basePath + targetFilePath);

        targetFile.deleteOnExit();
        sourceFile.renameTo(targetFile);

        return targetFilePath;
    }

    public static void writeMdContent(String mdFilePath, String mdContent) {
        try {
            BufferedWriter writer= new BufferedWriter(new FileWriter(mdFilePath));
            writer.write(mdContent);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static String readMdContent(String mdFilePath) {
        StringBuffer mdContent = new StringBuffer();
        try {
            BufferedReader reader = new BufferedReader(new FileReader(mdFilePath));
            String line;
            while ((line = reader.readLine()) != null) {
                mdContent.append(line).append("\n");
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return mdContent.toString();
    }

    public static String generateDownloadName(){
        return "CRUDBoy" + IDUtils.generateSimpleUUID() + ".zip";
    }

    //public static String readMdContent(String mdFilePath) {
    //    String mdContent = "";
    //    try {
    //        mdContent = new String(Files.readAllBytes(Paths.get(mdFilePath)));
    //        //Parser parser = Parser.builder().build();
    //        //Node document = parser.parse(content);
    //        //HtmlRenderer renderer = HtmlRenderer.builder().build();
    //        //String html = renderer.render(document);
    //    } catch (IOException e) {
    //        e.printStackTrace();
    //    }
    //
    //    return mdContent;
    //}

    private static String genreteMdFileName(){
        return "/upload/md/" + IDUtils.generateSimpleUUID() + ".md";
    }

}
